package com.qihunet.springbootjwt.service.impl;


import com.qihunet.springbootjwt.config.JwtTokenUtil;
import com.qihunet.springbootjwt.constant.ErrorDetail;
import com.qihunet.springbootjwt.exception.BusinessException;
import com.qihunet.springbootjwt.persistent.entity.UserInfo;
import com.qihunet.springbootjwt.request.LoginRequest;
import com.qihunet.springbootjwt.response.LoginResponse;
import com.qihunet.springbootjwt.service.AuthenticationService;
import com.qihunet.springbootjwt.service.UserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author gary
 */
@Service
public class AuthenticationServiceImpl implements AuthenticationService {

    private Logger logger = LoggerFactory.getLogger(AuthenticationServiceImpl.class);

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public LoginResponse loginPlatform(HttpServletRequest request, LoginRequest loginWrapper) throws BusinessException {
        LoginResponse response = new LoginResponse();
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(
                loginWrapper.getUsername(),
                loginWrapper.getPassword());
        try {
            final Authentication authentication = authenticationManager.authenticate(upToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }catch (AuthenticationException ex){
            if(ex instanceof DisabledException){
                throw new BusinessException(ErrorDetail.DISABLE_USER);
            }
            throw new BusinessException(ErrorDetail.AUTH_INVALID_PASSWORD_USERNAME);
        }
        UserInfo userInfo = userInfoService.findByUsername(loginWrapper.getUsername());

        if(!userInfo.getIsEnabled()){
            throw new BusinessException(ErrorDetail.DISABLE_USER);
        }

        List<String>  roles= userInfoService.findUserPermissionByUserIdAndUserType(userInfo);
        String token = jwtTokenUtil.generateToken(userInfo,roles);

        response.setToken(token);
        response.setId(userInfo.getDisplayUserId());
        response.setUserType(userInfo.getUserType());
        return response;
    }


}